package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.uu.view.AutoChangeViewPager;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseFragment;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.activity.CmnProductionListActivity;
import com.hemaapp.yjnh.activity.CmnProductionDetailActivity;
import com.hemaapp.yjnh.activity.ImageCarouselHeadClickListener;
import com.hemaapp.yjnh.activity.SearchActivity;
import com.hemaapp.yjnh.adapter.LiangkuAssort1Adapter;
import com.hemaapp.yjnh.adapter.LiangkuAssort2Adapter;
import com.hemaapp.yjnh.adapter.LiangkuRecommodAdapter;
import com.hemaapp.yjnh.bean.AdImage;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.BlogType;
import com.hemaapp.yjnh.view.ImageCarouselBanner;
import com.hemaapp.yjnh.view.YjnhGridView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 粮库
 */
public class LiangkuFragment extends BaseFragment implements OnClickListener {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_right_img)
    ImageView titleRightImg;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.recycler_assort_1)
    RecyclerView recyclerAssort1;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;
    @Bind(R.id.image_carousel)
    ImageCarouselBanner imageCarouselBanner;
    @Bind(R.id.grid_recommod)
    YjnhGridView gridRecommod;
    @Bind(R.id.grid_assort_2)
    YjnhGridView gridAssort2;

    private ArrayList<AdImage> adImgs = new ArrayList<>();
    private ArrayList<BlogType> mTypes1 = new ArrayList<>();//一级分类
    private ArrayList<BlogType> mTypes2 = new ArrayList<>();//二级分类
    private ArrayList<Blog> recomonds = new ArrayList<>();
    private LiangkuAssort1Adapter assort1Adapter;
    private LiangkuAssort2Adapter assort2Adapter;
    private LiangkuRecommodAdapter recommodAdapter;
    private int page = 0;
    private BlogType curBlogType;//当前选择的一级分类

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_liangku);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        titleText.setText("粮库");
        titleLeftBtn.setVisibility(View.GONE);
        titleRightBtn.setVisibility(View.GONE);
        titleRightImg.setVisibility(View.VISIBLE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerAssort1.setLayoutManager(linearLayoutManager);
        refreshLoadmoreLayout.setOnStartListener(new OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page = 0;
                if (mTypes1.size() == 0) {//如果总分类下没数据，那么先刷新总分类
                    getNetWorker().getBlogTypeList("1", "0");//商品总分类
                    return;
                }
                if (curBlogType == null) {
                    refreshLoadmoreLayout.refreshFailed();
                    return;
                }
                getNetWorker().getLiangkuADList(curBlogType.getId());//广告
                getNetWorker().blogList("16", curBlogType.getName(), "1", "1", "", "", "1", "", "", "", "", "", "", "", "0");
                getNetWorker().getBlogTypeList("1", curBlogType.getId());//二级分类
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page++;
            }
        });
        refreshLoadmoreLayout.setLoadmoreable(false);
        getNetWorker().getBlogTypeList("1", "0");//商品总分类
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.title_right_img})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_right_img://搜索
                Intent itSearch = new Intent(getActivity(), SearchActivity.class);
                itSearch.putExtra("type", 8);
                itSearch.putExtra("assort", "粮库");
                startActivity(itSearch);
                break;
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void setListener() {
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
            case BLOG_LIST:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
            case BLOG_LIST:
                cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOGTYPE_LIST:
                HemaArrayResult<BlogType> typeResult = (HemaArrayResult<BlogType>) baseResult;
                if (typeResult == null || typeResult.getObjects() == null)
                    return;
                String parentid = netTask.getParams().get("parentid");
                if (parentid.equals("0")) {//一级分类
                    mTypes1.clear();
                    mTypes1.addAll(typeResult.getObjects());
                    if (mTypes1.size() > 0) {
                        mTypes1.get(0).setChecked(true);
                        curBlogType = mTypes1.get(0);
                        getNetWorker().getLiangkuADList(mTypes1.get(0).getId());//广告
                        getNetWorker().blogList("16", mTypes1.get(0).getName(), "1", "1", "", "", "1", "", "", "", "", "", "", "", "0");
                        getNetWorker().getBlogTypeList("1", mTypes1.get(0).getId());//二级分类
                    }
                    refreshAssort1();//刷新一级分类
                }else {
                    if (page == 0) {// 刷新
                        refreshLoadmoreLayout.refreshSuccess();
                        mTypes2.clear();
                        this.mTypes2.addAll(typeResult.getObjects());
                    } else {
                        refreshLoadmoreLayout.loadmoreSuccess();
                        if (typeResult.getObjects().size() > 0) {
                            this.mTypes2.addAll(typeResult.getObjects());
                        } else {
                            refreshLoadmoreLayout.setLoadmoreable(false);
                            XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                        }
                    }
                    refreshAssort2();//刷新一级分类
                }
                break;
            case BLOG_LIST:
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                recomonds.clear();
                this.recomonds.addAll(bResult.getObjects());
                refreshRecommod();
                break;
            case BLOG_TYPE_AD_LIST:
                HemaPageArrayResult<AdImage> aResult = (HemaPageArrayResult<AdImage>) baseResult;
                if (aResult == null || aResult.getObjects() == null)
                    return;
                adImgs.clear();
                adImgs.addAll(aResult.getObjects());
                initAdPager();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case BLOG_TYPE_AD_LIST:
            case BLOGTYPE_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(getActivity(), "获取商品信息失败，" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case BLOG_TYPE_AD_LIST:
            case BLOGTYPE_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(getActivity(), "获取信息失败，请稍后再试");
                break;
        }
    }

    private void refreshAssort1() {
        if (assort1Adapter == null) {
            assort1Adapter = new LiangkuAssort1Adapter(getActivity(), mTypes1, new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    for (BlogType item:mTypes1) {
                        item.setChecked(false);
                    }
                    mTypes1.get(position).setChecked(true);
                    curBlogType = mTypes1.get(position);
                    assort1Adapter.notifyDataSetChanged();
                    getNetWorker().getLiangkuADList(curBlogType.getId());//广告
                    getNetWorker().blogList("16", curBlogType.getName(), "1", "1", "", "", "1", "", "", "", "", "", "", "", "0");
                    getNetWorker().getBlogTypeList("1", curBlogType.getId());//二级分类
                }
            });
            recyclerAssort1.setAdapter(assort1Adapter);
        } else
            assort1Adapter.notifyDataSetChanged();
    }

    private void refreshAssort2() {
        if (assort2Adapter == null) {
            assort2Adapter = new LiangkuAssort2Adapter(getActivity(), mTypes2, new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(getActivity(), CmnProductionListActivity.class);
                    it.putExtra("title", mTypes2.get(position).getName());
                    it.putExtra("keytype", "16");
                    if (mTypes2.get(position).getName().equals("全部"))
                        it.putExtra("keyid", "无");
                    else
                        it.putExtra("keyid", mTypes2.get(position).getName());
                    it.putExtra("keyword", "");
                    it.putExtra("saleflag", "");
                    it.putExtra("topflag", "");
                    it.putExtra("cheapflag", "");
                    it.putExtra("score_percent", "");
                    it.putExtra("seller_id", "");
                    it.putExtra("district_name", "");
                    startActivity(it);
                }
            });
            gridAssort2.setAdapter(assort2Adapter);
        } else
            assort2Adapter.notifyDataSetChanged();
    }

    private void refreshRecommod() {
        if (recommodAdapter == null) {
            recommodAdapter = new LiangkuRecommodAdapter(getActivity(), recomonds, new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(getActivity(), CmnProductionDetailActivity.class);
                    it.putExtra("blog_id", recomonds.get(position).getId());
                    startActivity(it);
                }
            });
            gridRecommod.setAdapter(recommodAdapter);
        } else
            recommodAdapter.notifyDataSetChanged();
    }

    private void initAdPager() {
        ArrayList<String> urls = new ArrayList<>();
        for (AdImage item : adImgs) {
            urls.add(item.getImgurl());
        }
        int wide = (XtomWindowSize.getWidth(getActivity()))/10 *7;
        imageCarouselBanner.getLayoutParams().width = wide;
        imageCarouselBanner.getLayoutParams().height = wide*22/45;
        imageCarouselBanner.onInstance(getActivity(), urls, R.drawable.ad_show_indicator,
                new ImageCarouselHeadClickListener(getActivity(), adImgs, "5"));
    }
}
